package com.gauravk.audiovisualizersample.util;

import ohos.media.audio.*;

import java.io.InputStream;
import java.util.logging.Logger;

public class PlaySoundUtil {
    private final int SAMPLE_RATE = 192000;
    private AudioStreamInfo audioStreamInfo = null;
    private AudioRendererInfo audioRendererInfo = null;
    private AudioRenderer.PlayMode playMode = AudioRenderer.PlayMode.MODE_STREAM;
    private AudioRenderer audioRenderer = null;
    private InputStream soundInputStream = null;

    /**
     * PlaySoundUtil构造方法  初始化音频播放器
     */
    public PlaySoundUtil() {
        audioStreamInfo = new AudioStreamInfo.Builder().sampleRate(44100) // 44.1kHz
                .audioStreamFlag(AudioStreamInfo.AudioStreamFlag.AUDIO_STREAM_FLAG_MAY_DUCK) // 混音
                .encodingFormat(AudioStreamInfo.EncodingFormat.ENCODING_PCM_16BIT) // 16-bit PCM
                .channelMask(AudioStreamInfo.ChannelMask.CHANNEL_OUT_DEFAULT) // 双声道输出
                .streamUsage(AudioStreamInfo.StreamUsage.STREAM_USAGE_MEDIA) // 媒体类音频
                .build();

        audioRendererInfo = new AudioRendererInfo.Builder().audioStreamInfo(audioStreamInfo)
                .audioStreamOutputFlag(
                        AudioRendererInfo.AudioStreamOutputFlag.AUDIO_STREAM_OUTPUT_FLAG_DIRECT_PCM) // pcm格式的输出流
                .bufferSizeInBytes(1024)
                .isOffload(false) // false表示分段传输buffer并播放，true表示整个音频流一次性传输到HAL层播放
                .build();
        audioRenderer = new AudioRenderer(audioRendererInfo, playMode);
    }

    /**
     * 加载本地音频资源
     *
     * @param fileName
     * @param musicFinish
     */
    public void loadSound(String fileName, MusicFinish musicFinish) {
        String filePath = String.format("assets/entry/resources/rawfile/%s", fileName);
        soundInputStream = this.getClass().getClassLoader().getResourceAsStream(filePath);

        byte[] buffer = new byte[1024];
        int len;
        try {
            audioRenderer.start();
            while ((len = soundInputStream.read(buffer, 0, buffer.length)) != -1) {
                audioRenderer.write(buffer, 0, buffer.length);
            }
            soundInputStream.close();
        } catch (Exception e) {
            Logger.getGlobal().finest(e.getMessage());
        }
        if (audioRenderer.getState() == AudioRenderer.State.STATE_PLAYING) {
            audioRenderer.pause();
        }
        musicFinish.finish();
    }

    public AudioRenderer getAudioRenderer() {
        return this.audioRenderer;
    }
}
